package cn.agiledata.bank.common.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import cn.agiledata.bank.netReturn.logic.NetReturnMessage;

import com.vnv.infrastructure.web.ServletTools;

/**
 * 
 * @author 马贤波
 * 
 */
public class IOUtil {
	private IOUtil() {
	}

	/**
	 * 根据相对于工程的类路径根目录的路径得到绝对路径
	 * 
	 * @param relativePath
	 *            相对路径
	 * @return 绝对路径
	 */
	public static String getAbsolutePath(String relativePath) {
		String root = ServletTools.getServeltContextPath();
		File file = new File(root, relativePath);
		return file.getAbsolutePath();
	}

	/**
	 * 获取指定url中的内容
	 * 
	 * @see java.net.URLConnection.getContent()
	 */
	public static Object getUrlContent(String url) throws IOException {
		URLConnection connection = new URL(url).openConnection();
		connection.connect();
		return connection.getContent();
	}

	/**
	 * 获取所有请求参数拼凑成的参数串，形如“参数名=参数值&参数名=参数值&……”
	 * 
	 * @return 所有请求参数拼凑成的参数串
	 */
	private static String getParameterString(Map parameters) {
		String param = "";
		for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			param += "&" + entry.getKey() + "=" + entry.getValue();
		}
		param = param.substring(1);
		return param;
	}

	/**
	 * 通过POST方式向指定url提交指定的所有参数，并返回响应结果
	 * 
	 * @param url
	 *            url
	 * @param parameters
	 *            所有参数
	 * @return 响应结果
	 * @throws IOException
	 */
	public static String postUrl(String url, Map parameters) throws IOException {
		URLConnection connection = new URL(url).openConnection();
		connection.setDoOutput(true);
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		if (parameters != null) {
			writer.write(getParameterString(parameters));
		}
		writer.flush();
		writer.close();

		// zln 修正 20080407 begin 修正读取反馈页面会出现sun.io.MalformedInputException的问题
		BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
		StringBuffer sBuffer = new StringBuffer();
		String tempStr;
		byte[] b = new byte[1024];
		int i = 0;
		while ((i = bis.read(b)) > 0) {
			tempStr = new String(b, 0, i);
			sBuffer.append(tempStr);
		}
		// zln 修正 20080407 end

		return sBuffer.toString();
	}

	public static void postNetReturnUrl(String url, Map parameters) throws IOException {
		Timer timer = new Timer(true);
		NetReturnMessage task = new NetReturnMessage();
		String delay = task.getPara("netReturnMessDelay");
		String count = task.getPara("netReturnMessCount");
		parameters.put("count", count);
		task.setUrl(url);
		task.setParameters(parameters);
		timer.schedule(task, 1000, Integer.parseInt(delay));
	}

	/**
	 * 从指定输入流中读取一行字符串。一行以字符'\n'为末尾，文件末尾返回null
	 * 
	 * @param in
	 *            输入流
	 * @return 字符串行
	 * @throws IOException
	 */
	public static String readLine(InputStream in) throws IOException {
		List list = new ArrayList();
		int b = -1;
		while ((b = in.read()) >= 0) {
			char c = (char) b;
			if (c != '\n') {
				list.add(new Character(c));
			} else {
				break;
			}
		}
		if (list.size() == 0) {
			return null;
		}
		byte[] bs = new byte[list.size()];
		for (int i = 0; i < list.size(); i++) {
			Character c = (Character) list.get(i);
			bs[i] = (byte) c.charValue();
		}
		return new String(bs);
	}
}
